package com.joker.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.joker.common.redis.service.RedisService;
import com.joker.order.config.PayConfig;
import com.joker.order.config.RabbitMQConfig;
import com.joker.order.domain.PmsPayWater;
import com.joker.order.service.IPayService;
import com.joker.common.core.domain.Result;
import com.joker.order.service.OrderService;
import com.joker.order.service.PmsPayWaterService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lemon
 * @date 2024/12/30 21:02
 **/
@RestController
@RequestMapping("/alipay")
public class PayController {

    @Autowired
    private IPayService payService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PmsPayWaterService pmsPayWaterService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private OrderService orderService;

    @GetMapping("getToken")
    public Result getToken(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisService.setCacheObject(token,token,5L, TimeUnit.MINUTES);
        return Result.success(token);
    }

    @GetMapping(value = "/pay/{totalPrice}",produces = "text/html")
    //@CheckIdempotent //表示该接口需要做幂等性校验
    public String pay(@PathVariable String totalPrice,@RequestParam("skuIds") Long[] skuIds) throws AlipayApiException {
        return payService.generatePay(totalPrice,skuIds);
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        // 检查交易状态是否为成功
        if (!"TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            // 如果状态不是成功，则返回失败
            return "failure";
        }

        System.out.println("=========支付宝异步回调========");

        // 创建一个存储请求参数的Map
        Map<String, String> params = getRequestParams(request);

        // 提取支付信息
        // 商户订单号
        String tradeNo = params.get("out_trade_no");
        // 付款时间
        String gmtPayment = params.get("gmt_payment");
        // 支付宝交易号
        String alipayTradeNo = params.get("trade_no");

        // 验证支付宝返回的签名
        if (verifySignature(params)) {

            // 记录交易详情
            logTransactionDetails(params);
            //TODO 支付完成修改订单状态


        }
        // 返回成功响应给支付宝
        return "success";
    }

    /**
     * 提取请求参数的方法
     * @param request
     * @return
     */
    private Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        return params;
    }

    /**
     * 验证签名的方法
     * @param params
     * @return
     * @throws Exception
     */
    private boolean verifySignature(Map<String, String> params) throws Exception {
        return AlipaySignature.rsaCheckV1(params, payConfig.getAlipayPublicKey(), "UTF-8", "RSA2");
    }

    /**
     * 记录交易详情的方法
     * @param params
     */
    private void logTransactionDetails(Map<String, String> params) {
        System.out.println("交易名称: " + params.get("subject"));
        System.out.println("交易状态: " + params.get("trade_status"));
        System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
        System.out.println("商户订单号: " + params.get("out_trade_no"));
        System.out.println("交易金额: " + params.get("total_amount"));
        System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
        System.out.println("买家付款时间: " + params.get("gmt_payment"));
        System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));


        // 在此处进行更新订单为已支付的操作
        // 验签通过，处理支付成功逻辑
        PmsPayWater pmsPayWater = new PmsPayWater();
        pmsPayWater.setOutTradeNo(params.get("out_trade_no"));
        pmsPayWater.setTradeNo(params.get("trade_no"));
        pmsPayWater.setTotalAmount(params.get("total_amount"));
        pmsPayWater.setSubject(params.get("subject"));
        pmsPayWater.setTradeStatus(params.get("trade_status"));
        pmsPayWater.setGmtPayment(params.get("gmt_payment"));
        pmsPayWater.setBuyerId(params.get("buyer_id"));
        pmsPayWater.setBuyerPayAmount(params.get("buyer_pay_amount"));

        pmsPayWaterService.insertPayWater(pmsPayWater);

    }
}
